<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠券名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:askCoupon:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:askCoupon:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:askCoupon:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:askCoupon:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="askCouponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id" v-if="true"/>
      <el-table-column label="优惠券名称" align="center" prop="name"/>
      <el-table-column label="使用类型" align="center" prop="useType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coupon_use_type" :value="scope.row.useType"/>
        </template>
      </el-table-column>
      <el-table-column label="面值" align="center" prop="money"/>
      <el-table-column label="发放总数" align="center" prop="total"/>
      <el-table-column label="剩余数量" align="center" prop="lastTotal"/>

      <!--      <el-table-column label="订单" align="center" prop="primaryKey"/>-->
      <el-table-column label="最低消费" align="center" prop="minPrice"/>
      <!--      <el-table-column label="可领取开始时间" align="center" prop="receiveStartTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.receiveStartTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="可领取结束时间" align="center" prop="receiveEndTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.receiveEndTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--            </el-table-column>-->
      <el-table-column label="可使用时间范围 开始时间" align="center" prop="useStartTime" width="180">
        <template slot-scope="scope" v-if="scope.row.isFixedTime === '1'">
          <span>{{ parseTime(scope.row.useStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="可使用时间范围 结束时间" align="center" prop="useEndTime" width="180">
        <template slot-scope="scope" v-if="scope.row.isFixedTime === '1'">
          <span>{{ parseTime(scope.row.useEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope" v-if="scope.row.isFixedTime === '0'">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="天数" align="center" prop="day">
        <template slot-scope="scope" v-if="scope.row.isFixedTime === '0'">
          <span>{{ scope.row.day }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领取类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coupon_get_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort"/>
      <!--      <el-table-column label="状态" align="center" prop="status"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:askCoupon:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:askCoupon:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改咨询优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称"/>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="useType">
          <el-select v-model="form.useType" placeholder="请输入优惠券类型" clearable>
            <el-option
              v-for="dict in dict.type.coupon_use_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券面值" prop="money">
          <el-input v-model="form.money" placeholder="请输入兑换的优惠券面值"/>
        </el-form-item>
        <el-form-item label="使用门槛">
          <el-radio-group v-model="threshold">
            <el-radio :label="false">无门槛</el-radio>
            <el-radio :label="true">有门槛</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠券最低消费" prop="minPrice" v-if="threshold">
          <el-input-number v-model="form.minPrice" :min="1" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="使用有效期">
          <el-radio-group v-model="form.isFixedTime" @change="changeTime">
            <el-radio label="0">天数</el-radio>
            <el-radio label="1">时间段</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用有效期限（天）" prop="day" v-if="form.isFixedTime === '0'">
          <el-input-number v-model="form.day" :min="0" :max="999" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="使用有效期限" v-if="form.isFixedTime === '1'">
          <el-date-picker
            style="width: 550px"
            v-model="termTime"
            type="datetimerange"
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            :picker-options="pickerOptions"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领取方式" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="0">手动领取</el-radio>
            <el-radio label="1">新人券</el-radio>
            <el-radio label="2">赠送券</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否限量" prop="isLimited">
          <el-radio-group v-model="form.isLimited">
            <el-radio label="0">限量</el-radio>
            <el-radio label="1">不限量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布数量" prop="total" v-if="form.isLimited === '0'">
          <el-input-number v-model="form.total" :min="1" label="排序"></el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">开启</el-radio>
            <el-radio label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listAskCoupon, getAskCoupon, delAskCoupon, addAskCoupon, updateAskCoupon} from "@/api/system/askCoupon";
import {addDateRange} from "@/utils/ruoyi";

export default {
  name: "AskCoupon",
  dicts: ['coupon_use_type', 'coupon_get_type'],
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          // return time.getTime() < new Date().setTime(new Date().getTime() - 3600 * 1000 * 24); //不限制未来时间
          return time.getTime() < Date.now() - 8.64e7 || time.getTime() > Date.now() + 600 * 8.64e7; //限制未来时间
        }
      },
      termTime: [],
      // 门槛开关
      threshold: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 咨询优惠券表格数据
      askCouponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        money: undefined,
        isLimited: undefined,
        total: undefined,
        lastTotal: undefined,
        useType: undefined,
        primaryKey: undefined,
        minPrice: undefined,
        receiveStartTime: undefined,
        receiveEndTime: undefined,
        isFixedTime: undefined,
        useStartTime: undefined,
        useEndTime: undefined,
        day: undefined,
        type: undefined,
        sort: undefined,
        status: undefined,
      },
      // 表单参数
      form: {
        userType: '0',
        type: '0',
        status: '0',
        isLimited: '0',
        isFixedTime: '0',
        params: {}
      },
      // 表单校验
      rules: {
        id: [
          {required: true, message: "优惠券表ID不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "优惠券名称不能为空", trigger: "blur"}
        ],
        money: [
          {required: true, message: "兑换的优惠券面值不能为空", trigger: "blur"}
        ],
        isLimited: [
          {required: true, message: "是否限量, 默认0 不限量， 1限量不能为空", trigger: "blur"}
        ],
        total: [
          {required: true, message: "发放总数不能为空", trigger: "blur"}
        ],
        lastTotal: [
          {required: true, message: "剩余数量不能为空", trigger: "blur"}
        ],
        useType: [
          {required: true, message: "使用类型 1 全场通用, 2 商品券, 3 品类券不能为空", trigger: "change"}
        ],
        status: [
          {required: true, message: "状态不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    changeTime() {
      const time = this.form.isFixedTime
      if (time === '0') {
        this.termTime = []
      }

      if (time === '1') {
        this.form.day = 0
      }

    },
    /** 查询咨询优惠券列表 */
    getList() {
      this.loading = true;
      listAskCoupon(this.queryParams).then(response => {
        this.askCouponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        money: undefined,
        isLimited: undefined,
        total: undefined,
        lastTotal: undefined,
        useType: undefined,
        primaryKey: undefined,
        minPrice: undefined,
        receiveStartTime: undefined,
        receiveEndTime: undefined,
        isFixedTime: undefined,
        useStartTime: undefined,
        useEndTime: undefined,
        day: undefined,
        type: undefined,
        sort: undefined,
        status: 0,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加咨询优惠券";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getAskCoupon(id).then(response => {
        this.loading = false;
        this.form = response.data;
        if (this.form.useStartTime) {
          this.termTime = []
          this.termTime[0] = this.form.useStartTime
          this.termTime[1] = this.form.useEndTime
        }

        this.open = true;
        this.title = "修改咨询优惠券";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.termTime) {
            let search = {}
            search.useStartTime = this.termTime[0]
            search.useEndTime = this.termTime[1]
            this.form.params = search
          } else {
            this.form.params = null
          }

          if (this.form.id != null) {
            updateAskCoupon(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addAskCoupon(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除咨询优惠券编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delAskCoupon(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/askCoupon/export', {
        ...this.queryParams
      }, `askCoupon_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
